package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    private final CategoryBrandService categoryBrandService;

    public CategoryServiceImpl(CategoryBrandService categoryBrandService) {
        this.categoryBrandService = categoryBrandService;
    }

    @Override
    public CategoryDTO findCategoryById(Long id) {
        return new CategoryDTO(this.getById(id));
    }

    @Override
    public List<CategoryDTO> listCategoryById(List<Long> ids) {
        return CategoryDTO.convertEntityList(this.listByIds(ids));
    }

    @Override
    public List<CategoryDTO> listCategoryParent(Long pid) {

        return CategoryDTO.convertEntityList(
                this.query().eq(pid != null, "parent_id", pid).list());
    }

    @Override
    public List<CategoryDTO> listCategoryBrand(Long bid) {

        //select *from tb_category_brand where brand_id =#{brand_id}
        List<Long> categoryIds = this.categoryBrandService.query()
                .eq("brand_id", bid)
                .list()
                .stream()
                .map(CategoryBrand::getCategoryId)
                .collect(Collectors.toList());

    /*    //select category_id from tb_category_brand where brand_id =#{brandId}
        List<CategoryBrand> categoryBrands = this.categoryBrandService.query()
                .select("category_id")
                .eq("brand_id", bid)
                .list();*/

        //TODO 当做业务时对象不是声明的，是外部获取的，则必定需要检查，为空特性
        if (CollectionUtils.isEmpty(categoryIds)) {
            throw new LyException(204, "该品牌没有对应的分类");
        }

        return this.listCategoryById(categoryIds);
    }

}
